package fr.dauphine.td3.security;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;

import fr.dauphine.td3.bdd.UtilisateurDAO;
import fr.dauphine.td3.emp.Utilisateur;

@SuppressWarnings("serial")
public class CustomAuthenticationProvider implements AuthenticationProvider {

	@Autowired
	private UtilisateurDAO utilisateurDAO;
	
	private static Map<String, String> SIMPLE_USERS = new HashMap<String, String>();
	private static Map<String, Integer> USERS_ADMIN = new HashMap<String, Integer>();

	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {

		List<Utilisateur> lu = new ArrayList<Utilisateur>();
		
		lu = utilisateurDAO.get();
		
		Iterator<Utilisateur> it = lu.iterator();
		
		Utilisateur u;
		
		while(it.hasNext()){
			u = it.next();
			
			if (u.getValide() == 1) {
			
				SIMPLE_USERS.put(u.getLogin(), u.getPassword());
				USERS_ADMIN.put(u.getLogin(), u.getAdministrateur());
			
			}
		}
		
		String principal = (String) authentication.getPrincipal();
		String password = (String) authentication.getCredentials();
		
		password = DigestUtils.md5Hex(password);
		
		if (SIMPLE_USERS.containsKey(principal) && SIMPLE_USERS.get(principal).equals(password)) {
			//C'est un utilisateur
			int administrateur = USERS_ADMIN.get(principal).intValue();
			
			final GrantedAuthority gai;
			
			if (administrateur == 0) {
				
				 gai = new GrantedAuthority() {

					public String getAuthority() {
						return "ROLE_USER";
					}

				};
			} else {
				
				 gai = new GrantedAuthority() {

					public String getAuthority() {
						return "ROLE_ADMIN";
					}

				};
			}
			
			
			List<GrantedAuthority> authorithies = new ArrayList<GrantedAuthority>();
			authorithies.add(gai);
			return new UsernamePasswordAuthenticationToken(principal, password, authorithies);

		}
		throw new BadCredentialsException("Mauvaise authentification : " + principal);
	}

	public boolean supports(Class aClass) {
		return true;
	}
}
